package com.example.rabbitmqdemo.hellorabbitmq.pubsub;

import com.example.rabbitmqdemo.hellorabbitmq.CommonUtil;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Slf4j
public class ConsumerPubSub {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = CommonUtil.getFactory();
        Connection connection = factory.newConnection();
        MyConsumer consumer_01 = new MyConsumer(connection.createChannel(), ProducerPubSub.QUEUE_01);
        MyConsumer consumer_02 = new MyConsumer(connection.createChannel(), ProducerPubSub.QUEUE_02);
        consumer_01.start();
        consumer_02.start();

    }


    static class MyConsumer extends Thread {
        private Channel channel;
        private String queueName;


        public MyConsumer(Channel channel, String queueName) {
            super(queueName);
            this.channel = channel;
            this.queueName = queueName;
        }


        @Override
        public void run() {
            try {
                String name = Thread.currentThread().getName();
                this.channel.basicConsume(this.queueName, new DefaultConsumer(this.channel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                        log.info("-- {} {}", name, new String(body));
                        Thread.yield();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
